package code.example.base.util.concurrent.container;

import code.example.tool.LogFactory;

import java.util.IdentityHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 测试并发集合 conncurrentLinkedNodes
 */
public class TestConcurrentLinkNodes {

    public void test(){
        AtomicInteger id = new AtomicInteger();
        int maxValue = 100000;
        IdentityHashMap identityHashMap = new IdentityHashMap(maxValue);
        ConcurrentLinkNodes<Long > nodes = new ConcurrentLinkNodes<Long>();
        ExecutorService executorService =  Executors.newFixedThreadPool(30);

        IntegerRunnable integerRunnable = new IntegerRunnable(id,identityHashMap,nodes,maxValue);
        for(int i=0;i<300;i++){
            executorService.execute(integerRunnable);
        }
        //executorService.shutdown();
        try {
            executorService.shutdown();
            executorService.awaitTermination(1, TimeUnit.DAYS);
        }catch (Exception e){}
    }
    class IntegerRunnable implements  Runnable{
        AtomicInteger id = null;
        Map<Long,Long> longMap= null;
        ConcurrentLinkNodes<Long > nodes = null;
        int maxValue ;
        public IntegerRunnable(AtomicInteger id ,Map<Long,Long> longMap,  ConcurrentLinkNodes<Long > nodes,int maxValue) {
            this.id = id;
            this.longMap = longMap;
            this.nodes = nodes;
            this.maxValue = maxValue;
        }
        @Override
        public void run() {
            AtomicInteger id  = this.id;

            ConcurrentLinkNodes<Long > nodes = this.nodes;
            while(true){
             /*   try {
                    TimeUnit.SECONDS.sleep(10);
                }catch (Exception   e){
                    e.printStackTrace();
                }*/
                long value = id.incrementAndGet();
                if(value > maxValue){
                    LogFactory.getLog().info("finish");
                    return;
                }
                if(value %10000 ==0){
                    LogFactory.getLog().info(Long.toString(value));
                }
                nodes.offer(value);

                Long  pollValue = nodes.poll();
                if(pollValue == null){
                    LogFactory.getLog().info("poll() ==null");
                    throw new RuntimeException("poll() ==null");

                }

            }

        }
    }
    public static void main(String args []){
        new TestConcurrentLinkNodes().test();
    }

}
